/**
 * Cloudnote Server
 * @author Wangtd
 */
const express = require('express');
const favicon = require('serve-favicon');
const session = require('express-session');
const bodyParser = require('body-parser');
const cookieParser = require("cookie-parser");

const config = require('./config.js');
const util = require('./lib/util.js');
const router = require('./lib/router.js');
const security = require('./lib/security.js');
const git = require('./lib/git.js');

var app = express();
var basePath = (config.debug ? 'app' : 'dist');

// favicon
app.use(favicon(util.paths(basePath + '/images/favicon.ico')));

// cookie & session
app.use(cookieParser());
app.use(session(config.sessionConfig));

// security
util.writeFileSync(config.workDir + '/users.json', '[]');
app.use(/^\/(?!app|note\/auth)\/?.+$/, security.checkPermission([/^(?!\/note\/).+/, '/note/file/']));

// homepage
app.use('/', function(request, response, next) {
    var url = request.url;
    if (url == '/') {
        var homepage = basePath + '/index.html';
        response.writeHead(200, { 'content-type': 'text/html' });
        response.end(util.readFileSync(util.paths(homepage)));
    } else if (url == '/app/') {
        response.redirect('/');
    } else {
        next();
    }
});
// app
app.use('/app', express.static(util.paths(basePath)));
// parameter
app.use(bodyParser.urlencoded({ limit: '100mb', extended: false }));
app.use(bodyParser.json({ type: 'application/json', limit: '10mb' }));
// router
app.use(router);
// notes
util.mkdirsSync(config.noteDir);
// images
util.mkdirsSync(config.imageDir);

// init git and task
git.initRepository();
git.startCommitTask();

// start http server
app.listen(config.port, '0.0.0.0', function(error) {
    if (error) {
        console.error(error);
    } else {
        console.log('Cloudnote server is running at http://localhost:%d/', config.port);
    }
});
